<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">时间戳转换器</h1>
        <p class="text-gray-600">在时间戳（秒或毫秒）与可读时间之间相互转换。支持本地时间与 UTC，支持复制与快速设置当前时间。</p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- 时间戳 -> 可读时间 -->
        <div class="bg-white p-6 rounded-lg shadow">
          <h2 class="text-lg font-medium mb-3">时间戳 → 可读时间</h2>
          <label class="block text-sm text-gray-600">输入时间戳（秒或毫秒）</label>
          <div class="mt-2 flex space-x-2">
            <input v-model="timestampInput" @input="onTimestampInput" placeholder="例如：1600000000 或 1600000000000" class="flex-1 border rounded px-3 py-2" />
            <button @click="setNowTimestamp" class="bg-gradient-to-r from-green-500 to-green-600 text-white px-3 py-2 rounded">当前时间戳</button>
          </div>

          <div class="mt-4 space-y-2">
            <div>
              <div class="text-xs text-gray-500">检测</div>
              <div class="text-sm text-gray-800">
                类型：<span class="font-medium">{{ detectedTimestampType }}</span>
              </div>
            </div>

            <div>
              <div class="text-xs text-gray-500">本地时间</div>
              <div class="flex items-center justify-between">
                <div class="text-sm font-medium text-gray-800">{{ localTime || '-' }}</div>
                <div class="flex items-center space-x-2">
                  <button @click="copyText(localTime)" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">复制</button>
                  <button @click="fillDateInputWithLocal" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">填入下方日期</button>
                </div>
              </div>
            </div>

            <div>
              <div class="text-xs text-gray-500">UTC 时间</div>
              <div class="flex items-center justify-between">
                <div class="text-sm font-medium text-gray-800">{{ utcTime || '-' }}</div>
                <div>
                  <button @click="copyText(utcTime)" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">复制</button>
                </div>
              </div>
            </div>

            <div>
              <div class="text-xs text-gray-500">备注</div>
              <div class="text-sm text-gray-700">秒级时间戳长度 ≤ 10；毫秒级长度 ≥ 13。若输入不能解析，将显示 "-"。</div>
            </div>
          </div>
        </div>

        <!-- 可读时间 -> 时间戳 -->
        <div class="bg-white p-6 rounded-lg shadow">
          <h2 class="text-lg font-medium mb-3">可读时间 → 时间戳</h2>

          <label class="block text-sm text-gray-600">输入日期（支持 ISO / 本地可读）</label>
          <input v-model="dateInput" @input="onDateInput" placeholder="例如：2020-09-13 12:00:00 或 2020-09-13T12:00:00Z" class="mt-2 w-full border rounded px-3 py-2" />

          <div class="mt-3 flex space-x-2">
            <button @click="setNowDate" class="bg-gradient-to-r from-green-500 to-green-600 text-white px-3 py-2 rounded">使用当前时间</button>
            <button @click="pasteLocalTimeToTimestamp" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">填入上方时间戳</button>
          </div>

          <div class="mt-4 space-y-2">
            <div>
              <div class="text-xs text-gray-500">解析结果</div>
              <div class="flex items-center justify-between">
                <div class="text-sm font-medium text-gray-800">{{ parsedDateReadable || '-' }}</div>
                <div>
                  <button @click="copyText(parsedDateReadable)" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">复制</button>
                </div>
              </div>
            </div>

            <div>
              <div class="text-xs text-gray-500">时间戳（秒）</div>
              <div class="flex items-center justify-between">
                <div class="text-sm font-medium text-gray-800">{{ timestampSeconds || '-' }}</div>
                <div>
                  <button @click="copyText(timestampSeconds)" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">复制</button>
                </div>
              </div>
            </div>

            <div>
              <div class="text-xs text-gray-500">时间戳（毫秒）</div>
              <div class="flex items-center justify-between">
                <div class="text-sm font-medium text-gray-800">{{ timestampMillis || '-' }}</div>
                <div>
                  <button @click="copyText(timestampMillis)" class="bg-gray-100 text-gray-800 px-3 py-1 rounded border">复制</button>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
     </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const timestampInput = ref('')
const dateInput = ref('')

const detectedTimestampType = ref('-')
const localTime = ref('')
const utcTime = ref('')

const parsedDateReadable = ref('')
const timestampSeconds = ref('')
const timestampMillis = ref('')

function normalizeNumberString(s) {
  return String(s).trim()
}

function onTimestampInput() {
  const s = normalizeNumberString(timestampInput.value)
  if (!s) {
    detectedTimestampType.value = '-'
    localTime.value = ''
    utcTime.value = ''
    return
  }

  // remove commas/spaces
  const cleaned = s.replace(/[ ,]/g, '')
  if (!/^[-+]?\d+(\.\d+)?$/.test(cleaned)) {
    detectedTimestampType.value = '无效数字'
    localTime.value = ''
    utcTime.value = ''
    return
  }

  // detect based on length
  const digits = cleaned.replace(/[^0-9]/g, '')
  let ms = null
  if (digits.length <= 10) {
    detectedTimestampType.value = '秒（自动识别）'
    ms = Number(cleaned) * 1000
  } else if (digits.length >= 13) {
    detectedTimestampType.value = '毫秒（自动识别）'
    ms = Number(cleaned)
  } else {
    // ambiguous, try to guess: if number > 1e12 treat as ms else seconds
    const n = Number(cleaned)
    if (n > 1e12) {
      detectedTimestampType.value = '毫秒（猜测）'
      ms = n
    } else {
      detectedTimestampType.value = '秒（猜测）'
      ms = n * 1000
    }
  }

  const d = new Date(ms)
  if (isNaN(d.getTime())) {
    localTime.value = ''
    utcTime.value = ''
    return
  }

  localTime.value = formatLocal(d)
  utcTime.value = formatUTC(d)
}

function onDateInput() {
  const s = dateInput.value && dateInput.value.trim()
  if (!s) {
    parsedDateReadable.value = ''
    timestampSeconds.value = ''
    timestampMillis.value = ''
    return
  }

  // Try Date.parse first (handles ISO), else try replacing space with T
  let ms = Date.parse(s)
  if (isNaN(ms)) {
    // try to replace space between date and time with 'T' and append local timezone if missing
    const replaced = s.replace(' ', 'T')
    ms = Date.parse(replaced)
  }

  if (isNaN(ms)) {
    // Try parsing by creating a Date from components (simple formats)
    // fallback: new Date(s)
    const d2 = new Date(s)
    if (isNaN(d2.getTime())) {
      parsedDateReadable.value = '无法解析'
      timestampSeconds.value = ''
      timestampMillis.value = ''
      return
    }
    ms = d2.getTime()
  }

  const d = new Date(ms)
  parsedDateReadable.value = formatLocal(d)
  timestampMillis.value = String(ms)
  timestampSeconds.value = String(Math.floor(ms / 1000))
}

function formatLocal(d) {
  // YYYY-MM-DD HH:mm:ss (local)
  const Y = d.getFullYear()
  const M = pad(d.getMonth() + 1)
  const D = pad(d.getDate())
  const hh = pad(d.getHours())
  const mm = pad(d.getMinutes())
  const ss = pad(d.getSeconds())
  return `${Y}-${M}-${D} ${hh}:${mm}:${ss}`
}

function formatUTC(d) {
  const Y = d.getUTCFullYear()
  const M = pad(d.getUTCMonth() + 1)
  const D = pad(d.getUTCDate())
  const hh = pad(d.getUTCHours())
  const mm = pad(d.getUTCMinutes())
  const ss = pad(d.getUTCSeconds())
  return `${Y}-${M}-${D} ${hh}:${mm}:${ss} UTC`
}

function pad(n) {
  return String(n).padStart(2, '0')
}

function setNowTimestamp() {
  const nowMs = Date.now()
  timestampInput.value = String(nowMs)
  onTimestampInput()
}

function setNowDate() {
  const now = new Date()
  dateInput.value = formatLocal(now)
  onDateInput()
}

function copyText(text) {
  if (!text && text !== 0) {
    return
  }
  const t = String(text)
  if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(t).then(() => {
      // Optional: show a small temporary message (not implemented)
    }).catch(() => {
      fallbackCopy(t)
    })
  } else {
    fallbackCopy(t)
  }
}

function fallbackCopy(t) {
  const ta = document.createElement('textarea')
  ta.value = t
  document.body.appendChild(ta)
  ta.select()
  try { document.execCommand('copy') } catch (e) {}
  ta.remove()
}

function fillDateInputWithLocal() {
  if (localTime.value) {
    dateInput.value = localTime.value
    onDateInput()
  }
}

function pasteLocalTimeToTimestamp() {
  // take parsedDateReadable (if exists) and set timestampInput to milliseconds
  if (timestampMillis.value) {
    timestampInput.value = timestampMillis.value
    onTimestampInput()
  }
}

// helpers
function fallbackNumber(n) {
  return n == null || n === '' ? '-' : String(n)
}

// expose computed-ish values to template via refs (keep updated)
// watch-like: keep initial empty values

// Wire simple watchers: when timestampInput or dateInput change, conversion functions run via @input handlers

// SEO
useHead({
  title: '时间戳转换 - 八八在线工具',
  meta: [
    { name: 'description', content: '在线时间戳与可读时间互转工具，支持秒/毫秒、UTC与本地时间，支持复制与当前时间设置' }
  ]
})
</script>
